import 'dart:io';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_settings_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_add_folder/service/upload_media_library_service.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_add_folder/terminal_detail_add_folder_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import 'bean/terminal_detail_add_folder_response_bean.dart';
import 'widgets/terminal_detail_add_folder_bottom_widget.dart';
import 'widgets/terminal_detail_add_folder_grid_item_widget.dart';
import 'package:photo_preview/photo_preview_export.dart' as pv;
/// 终端详情添加文件
///
/// @author: zengxiangxi
/// @createTime: 2/5/21 11:51 AM
/// @specialDemand:
class TerminalDetailAddFolderPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "TerminalDetailAddFolderPage";

  final String hsn;
  final String branchname;

  const TerminalDetailAddFolderPage({Key key, this.hsn, this.branchname}) : super(key: key);

  @override
  _TerminalDetailAddFolderPageState createState() =>
      _TerminalDetailAddFolderPageState();

  ///跳转方法
  ///返回第一个新图
  ///空的话没更新
  static Future<String> navigatorPush(BuildContext context, String hsn, String branchname) {
    print("终端详情添加文件: hsn-${hsn}");
    if (StringUtils.isEmpty(hsn)) {
      VgToastUtils.toast(context, "终端设备获取失败");
      return null;
    }
    return RouterUtils.routeForFutureResult<String>(
      context,
      TerminalDetailAddFolderPage(
        hsn: hsn,
        branchname: branchname,
      ),
      routeName: TerminalDetailAddFolderPage.ROUTER,
    );
  }
}

class _TerminalDetailAddFolderPageState extends BasePagerState<
    TerminalDetailAddFolderListItemBean,
    TerminalDetailAddFolderPage> with VgPlaceHolderStatusMixin {
  TerminalDetailAddFolderViewModel _viewModel;

  //选中list集合
  List<String> _selectedList = List();

  String _searchStr;

  ///完成上传集合
  ///（目的）上传完成后直接选中状态
  List<String> _completeUploadList = List();

  @override
  void initState() {
    super.initState();
    _viewModel =
        TerminalDetailAddFolderViewModel(this, widget.hsn, getSearchStrFunc: () => _searchStr);
    _viewModel.refresh();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(child: _toMainColumnWiget()),
    );
  }

  Widget _toMainColumnWiget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        // SizedBox(height: 12),
        // CommonSearchBarWidget(hintText: "搜索"),
        SizedBox(height: 12),
        Expanded(
          child: MixinPlaceHolderStatusWidget(
              emptyOnClick: () => _viewModel?.refresh(),
              errorOnClick: () => _viewModel?.refresh(),
              child: _toPullRefreshWidget()),
        ),
        TerminalDetailAddFolderBottomWidget(
          onUploadTap: _processUpload,
          onConfrimTap: _processConfirm,
          isAliveConfirm: !(_selectedList == null || _selectedList.isEmpty),
        ),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "请选择",
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      // rightWidget: _toSaveButtonWidget(),
    );
  }

  ///处理视频的逻辑
  void handleVideo(String localUrl, List<UploadMediaLibraryItemBean> _uploadList)async{
    //视频
    UploadMediaLibraryItemBean item = UploadMediaLibraryItemBean(
      localUrl: localUrl, mediaType: MediaType.video,);

    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();

    _uploadList.add(item);
    videoController.dispose();
    loading(false);
    String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
        singleflg: true, needUpload:true, currentHsn: widget?.hsn, hsns: widget?.hsn,
        itemList: _uploadList, branchname: widget?.branchname);
    if(StringUtils.isNotEmpty(result)){
      RouterUtils.pop(context);
    }
  }

  ///处理图片
  void handleImage(String localUrl, List<String> resultList, List<UploadMediaLibraryItemBean> _uploadList){
    //图片
    List<Future> taskList = resultList.reversed.map((element) {
      FileImage image = FileImage(File(element));
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info,
          bool _) async {
        double width = info.image.width + 0.0;
        double height = info.image.height + 0.0;

        if (width / height != 9.0 / 16.0) {
          // String clipPath = await MatisseUtil.clipOneImage(
          //   context,
          //   path: element,
          //   scaleX: 9,
          //   scaleY: 16,
          //   leftCancelWidget: _leftWidget(info,
          //       element, _uploadList, resultList.length),
          //   rightClipWidget: _rightWidget(),
          //   topLeftWidget: _topLeftWidget(),
          //   editorConfig: pv.EditorConfig(
          //       maxScale: 8.0,
          //       cropRectPadding:
          //       EdgeInsets.all(30),
          //       hitTestSize: 0,
          //       lineColor: Colors.white,
          //       cornerSize: Size(0, 0),
          //       lineHeight: 2,
          //       cropAspectRatio: (9 ?? 1.0) / (16 ?? 1.0),
          //       editorMaskColorHandler: (context, bo) {
          //         return Color(0x80000000);
          //       }
          //   ),
          // );
          String clipPath = await MatisseUtil.clipOneImage(context,
            path: element, scaleX: 9, scaleY: 16,
            isCanMixRadio: true,
            // leftCancelWidget: _leftWidget(info, element, _uploadList, resultList.length),
            // rightClipWidget: _rightWidget(),
            topLeftWidget: _topLeftWidget(),
            keepRadioWidget: _keepWidget(info, element, _uploadList, resultList.length),
            rightTopClipWidget: _topRightWidget(),
              onRequestPermission: (msg)async{
                bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: msg,
                  cancelText: "取消",
                  confirmText: "去授权",
                );
                if (result ?? false) {
                  PermissionUtil.openAppSettings();
                }
              }
          );
          if(clipPath == null){
            return;
          }
          if (StringUtils.isNotEmpty(clipPath)) {
            FileImage clipImage = FileImage(File(clipPath));
            clipImage
                .resolve(new ImageConfiguration())
                .addListener(new ImageStreamListener((ImageInfo info, bool _) async {
              _uploadList.add(UploadMediaLibraryItemBean(
                localUrl: clipPath,
                mediaType: MediaType.image,
                folderWidth: info.image.width,
                folderHeight: info.image.height,
              ));
              if (_uploadList.length == resultList.length) {
                String result = await MediaSettingsPage
                    .navigatorPushString(context, _uploadList[0],
                    singleflg: true,
                    needUpload: true,
                    currentHsn: widget?.hsn,
                    hsns: widget?.hsn,
                    itemList: _uploadList, branchname: widget?.branchname);
                if (StringUtils.isNotEmpty(result)) {
                  RouterUtils.pop(context);
                }
              }
            }));



          } else {
            if (_uploadList.length == resultList.length) {
              //判断是否是重复数据
              int count = 0;
              _uploadList.forEach((element) {
                if(localUrl == element.localUrl){
                  count++;
                }
              });
              if(count == 0){
                _uploadList.add(UploadMediaLibraryItemBean(
                    localUrl: localUrl,
                    mediaType: MediaType.image,
                  folderWidth: info.image.width,
                  folderHeight: info.image.height,));
              }
            }
          }
        }

        else {
          _uploadList.add(UploadMediaLibraryItemBean(
              localUrl: element,
              mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));

          if (_uploadList.length == resultList.length) {
            String result = await MediaSettingsPage.navigatorPushString(
                context, _uploadList[0],
                singleflg: true,
                needUpload: true,
                currentHsn: widget?.hsn,
                hsns: widget?.hsn,
                itemList: _uploadList, branchname: widget?.branchname);
            if (StringUtils.isNotEmpty(result)) {
              RouterUtils.pop(context);
            }
          }
        }
      }));

      return new Future(() {
        print(element);
      });
    }).toList();
    // Future future = Future.wait(taskList);
    // future.then((value) async {
    //
    //   String result = await MediaSettingsPage.navigatorPushString(
    //       context, _uploadList[0],
    //       singleflg: true,
    //       needUpload: true,
    //       currentHsn: widget?.hsn,
    //       hsns: widget?.hsn,
    //       itemList: _uploadList);
    //   if (StringUtils.isNotEmpty(result)) {
    //     RouterUtils.pop(context);
    //   }
    // });
  }

  void _processUpload() async {
    List<String> resultList = await MatisseUtil.selectAll(
        context: context,
        isCanMixSelect: false,
        maxImageSize: 9,
        maxVideoSize: 1,
        videoMemoryLimit: 500*1024,
        videoDurationLimit: 10*60,
        videoDurationMinLimit: 10,
        maxAutoFinish: false,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<UploadMediaLibraryItemBean> _uploadList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }

    if(resultList.length == 1 && MatisseUtil.isVideo(localUrl)){
      //视频
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, _uploadList);
    }else {
      if(resultList.length > 1){
        loading(true, msg: "图片处理中");
        int needClipCount = 0;
        int computeCount = 0;
        resultList.forEach((element) {
          FileImage image = FileImage(File(element));
          image.resolve(new ImageConfiguration())
              .addListener(
              new ImageStreamListener((ImageInfo info, bool _) async {
                _imageInfoMap[element] = info;
                double width = info.image.width + 0.0;
                double height = info.image.height + 0.0;
                if (width / height != 9.0 / 16.0) {
                  needClipCount++;
                }
                computeCount++;
                if (computeCount == resultList.length) {
                  loading(false);
                  if(needClipCount > 0){
                    bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "检测到${needClipCount}张图片长宽比不符合16:9，是否逐个裁剪处理？",
                        cancelText: "保持原比例",
                        confirmText: "去裁剪",
                        confirmBgColor: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF());
                    //去裁剪
                    if(result == null){
                      RouterUtils.pop(context);
                      return;
                    }
                    if (result ?? false) {
                      handleImage(localUrl, resultList, _uploadList);
                    } else {
                      //保持原图比例
                      resultList.forEach((element) {
                        _uploadList.add(UploadMediaLibraryItemBean(
                            localUrl: element,
                            mediaType: MediaType.image,
                          folderWidth: _imageInfoMap[element].image.width,
                          folderHeight: _imageInfoMap[element].image.height,));
                      });


                      String result = await MediaSettingsPage.navigatorPushString(
                          context, _uploadList[0],
                          singleflg: true,
                          needUpload: true,
                          currentHsn: widget?.hsn,
                          hsns: widget?.hsn,
                          itemList: _uploadList, branchname: widget?.branchname);
                      if (StringUtils.isNotEmpty(result)) {
                        RouterUtils.pop(context);
                      }
                    }
                  }else{
                    //保持原图比例
                    resultList.forEach((element) {
                      _uploadList.add(UploadMediaLibraryItemBean(
                          localUrl: element,
                          mediaType: MediaType.image,
                        folderWidth: _imageInfoMap[element].image.width,
                        folderHeight: _imageInfoMap[element].image.height,));
                    });

                    String result = await MediaSettingsPage.navigatorPushString(
                        context, _uploadList[0],
                        singleflg: true,
                        needUpload: true,
                        currentHsn: widget?.hsn,
                        hsns: widget?.hsn,
                        itemList: _uploadList, branchname: widget?.branchname);
                    if (StringUtils.isNotEmpty(result)) {
                      RouterUtils.pop(context);
                    }
                  }

                }
              }));
        });
      }else{
        handleImage(localUrl, resultList, _uploadList);
      }


    }
  }

  _doUpload(List<UploadMediaLibraryItemBean> uploadList){
    UploadMediaLibraryService service =
    UploadMediaLibraryService().setList(uploadList, widget?.hsn);
    if (service != null) {
      VgHudUtils.show(context, "正在上传");
      service.upload(VgBaseCallback(
          onSuccess: (list) {
            VgHudUtils.hide(context);
            VgToastUtils.toast(AppMain.context, "上传完成");
            //保留上传后的url
            print("上传成功后的列表：${list}");
            _saveUploadCompleteList(list);
            //刷新请求
            _viewModel?.refreshMultiPage();
            //通知首页更新n
            VgEventBus.global.send(MediaLibraryRefreshEven());
          }, onError: (msg) {
        VgHudUtils.hide(context);
        print("TerminalDetailAddFolderPage上传失败1:" + msg);
        VgToastUtils.toast(AppMain.context, "上传失败");
      }));
    }
  }

    Widget _leftWidget(ImageInfo info, String localUrl, List<UploadMediaLibraryItemBean> _uploadList, int totalSize){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(StringUtils.isNotEmpty(localUrl)){
          Navigator.of(context).pop();
          _uploadList.add(UploadMediaLibraryItemBean(
              localUrl: localUrl,
              mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));
          // bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0]);
          // if(result??false){
          //   _viewModel?.refreshMultiPage();
          // }
          if(_uploadList.length == totalSize){
            String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
                singleflg: true, needUpload:true,  currentHsn: widget?.hsn,
                hsns: widget?.hsn, itemList: _uploadList, branchname: widget?.branchname);
            if(StringUtils.isNotEmpty(result)) {
              RouterUtils.pop(context);
            }
          }

        }
      },
      child: Container(
        padding: EdgeInsets.only(bottom: 7.5),
        child: Text(
          "保持原图比例",
          style: TextStyle(
              fontSize: 15,
              color: Colors.white
          ),
        ),
      ),
    );
  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: VgColors.INPUT_BG_COLOR,
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  Widget _rightWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 96,
      height: 36,
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      selectedTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      unSelectTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      text: "确定裁剪",
      textSize: 15,
    );
  }

  Widget _keepWidget(ImageInfo info, String localUrl, List<UploadMediaLibraryItemBean> _uploadList, int totalSize){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(StringUtils.isNotEmpty(localUrl)){
          Navigator.of(context).pop();
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: localUrl,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));
          // bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0]);
          // if(result??false){
          //   _viewModel?.refreshMultiPage();
          // }
          if(_uploadList.length == totalSize){
            String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
                singleflg: true, needUpload:true,  currentHsn: widget?.hsn,
                hsns: widget?.hsn, itemList: _uploadList, branchname: widget?.branchname);
            if(StringUtils.isNotEmpty(result)) {
              RouterUtils.pop(context);
            }
          }

        }
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 5, vertical: 22),
        child: Container(
          height: 21.5,
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
          alignment: Alignment.center,
          child: Text(
            "原始比例",
            style: TextStyle(color: Color(0xffaaaaaa), fontSize: 12, height: Platform.isIOS ? 1.2 : 1.15),
          ),
        ),
      ),
    );
  }

  Widget _topRightWidget(){
    return Container(
      height: 23,
      width: 48,
      alignment: Alignment.center,
      margin: EdgeInsets.only(left: 15, right: 15, top: 11, bottom: 10),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        borderRadius: BorderRadius.circular(11.5),
      ),
      child: Text(
        "确定",
        style: TextStyle(
            fontSize: 12,
            color: Colors.white
        ),
      ),
    );
  }

  Widget _toPullRefreshWidget() {
    return VgPullRefreshWidget.bind(
      viewModel: _viewModel,
      state: this,
      child: GridView.builder(
        padding: EdgeInsets.only(left: 15, right: 15, top: 3, bottom: 20),
        itemCount: data?.length ?? 0,
        physics: BouncingScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 5,
          crossAxisSpacing: 5,
          childAspectRatio: 1,
        ),
        itemBuilder: (BuildContext context, int index) {
          return TerminalDetailAddFolderGridItemWidget(
            itemBean: data?.elementAt(index),
            onTap: (TerminalDetailAddFolderListItemBean itemBean) {
              _handleSelectedStatus(itemBean);
            },
          );
        },
      ),
    );
  }

  ///处理选中状态
  void _handleSelectedStatus(TerminalDetailAddFolderListItemBean itemBean) {
    if (itemBean == null || StringUtils.isEmpty(itemBean.id)) {
      VgToastUtils.toast(context, "错误资源");
      return;
    }
    if (itemBean.selectedNum == null || itemBean.selectedNum < 0) {
      _addLabel(itemBean.id);
    } else {
      _removeLabel(itemBean.id);
    }
  }

  void _addLabel(String selectedId) {
    _selectedList?.add(selectedId);
    _handleUpdateList(data);
  }

  void _removeLabel(String removeId) {
    _selectedList?.remove(removeId);
    _handleUpdateList(data);
  }

  void _handleUpdateList(List<TerminalDetailAddFolderListItemBean> list) {
    if (list == null || list.isEmpty) {
      return;
    }
    list?.removeWhere((element) => StringUtils.isEmpty(element?.id));
    // if(_selectedList == null || _selectedList.isEmpty){
    //   return;
    // }
    for (TerminalDetailAddFolderListItemBean item in list) {
      int positon = _selectedList.indexOf(item.id);
      if (positon == null || positon == -1) {
        item.selectedNum = null;
      } else {
        item.selectedNum = positon + 1;
      }
    }

    // print("打印结果"
    //     "\n"
    //     "${list.toString()}");
    setState(() {});
  }

  @override
  void setListData(List<TerminalDetailAddFolderListItemBean> list) {
    list?.removeWhere((element) => element == null);
    list = list?.toSet()?.toList();
    _handleUploadCompleteSelectedList(list);
    _handleEmptySelectedItemForList(list);
    _handleUpdateList(list);
    super.setListData(list);
  }

  ///处理上传完成后选中问题
  void _handleUploadCompleteSelectedList(List<TerminalDetailAddFolderListItemBean> list){
    if(_completeUploadList ==null || _completeUploadList.isEmpty || list == null || list.isEmpty){
      return;
    }
    for(TerminalDetailAddFolderListItemBean item in list){
      if(StringUtils.isEmpty(item?.picurl)){
        continue;
      }
      if(_completeUploadList.indexOf(item.picurl) != -1){
        _selectedList.add(item?.id);
        _completeUploadList?.remove(item.picurl);
      }
    }

  }

  ///去选中交集（避免更新资源移除后序列不正确）
  ///重点
  _handleEmptySelectedItemForList(
      List<TerminalDetailAddFolderListItemBean> list) {
    if (_selectedList == null || _selectedList.isEmpty) {
      return;
    }
    Set allIdList = list.map((e) => e?.id).toSet();
    if (allIdList == null || allIdList.isEmpty) {
      _selectedList?.clear();
      return;
    }
    //交集
    _selectedList = _selectedList.toSet().intersection(allIdList).toList();
    _selectedList.removeWhere((element) => StringUtils.isEmpty(element));
  }

  ///处理确定
  void _processConfirm() async{
    if (_selectedList == null || _selectedList.isEmpty) {
      VgToastUtils.toast(context, "请选择一项");
      return;
    }
    List<UploadMediaLibraryItemBean> _uploadList = List();
    data.forEach((element) {
      if(_selectedList.contains(element?.id)){
        int width;
        int height;
        if(StringUtils.isNotEmpty(element.picsize) && element.picsize.contains("*")){
          width = int.parse(element.picsize.split("*")[0]);
          height = int.parse(element.picsize.split("*")[1]);
        }
        _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: element.picurl,
            id: element?.id,
            videoLocalCover: (element?.videopic??""),
            mediaType: ("02" == element.type)?MediaType.video:MediaType.image,
          folderWidth: width,
          folderHeight: height,
          title: element.title??"",
          subtitle: element.subtitle??"",
          waterflg: element.waterflg??"",
          logoflg: element.logoflg??""
        ),

        );
      }
    });
    String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
        singleflg: true, currentHsn: widget?.hsn,
        hsns: widget?.hsn, itemList: _uploadList, branchname: widget?.branchname);
    if(StringUtils.isNotEmpty(result)){
      RouterUtils.pop(context);
    }
    // _viewModel?.saveListHttp(context, _selectedList);
  }
  
  void _saveUploadCompleteList(List<UploadMediaLibraryItemBean> uploadList){
    if(uploadList == null  || uploadList.isEmpty){
      return ;
    }
    List<String> tmpUrlList = List();
    for(UploadMediaLibraryItemBean item in uploadList){
      tmpUrlList.add(item?.netUrl);
    }
    tmpUrlList.removeWhere((element) =>StringUtils.isEmpty(element));
    if(tmpUrlList == null || tmpUrlList.isEmpty){
      return;
    }
    _completeUploadList?.addAll(tmpUrlList);
  }
}
